package ebj.common.aws;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.zip.GZIPOutputStream;

import org.apache.commons.compress.compressors.gzip.GzipUtils;
import org.apache.log4j.Logger;

import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.PutObjectRequest;

public class AWSFileStore {
    private static Logger logger = Logger.getLogger(AWSFileStore.class);
    
    private static PropertiesCredentials propertiesCredentials = null;
    static{
        ClassLoader classloader = Thread.currentThread().getContextClassLoader();
        InputStream is = classloader.getResourceAsStream("AwsCredentials.properties");
        logger.info("AWSCredentials 配置文件已加载.");
        try {
            propertiesCredentials = new PropertiesCredentials(is);
        } catch (IOException e) {
            logger.error("", e);
        }
    }
    
    public static String Save(String data) throws IOException {
        File file = File.createTempFile("tmp-", ".csv");
        file.deleteOnExit();

        Writer writer = new OutputStreamWriter(new FileOutputStream(file));
        writer.write(data);
        writer.flush();
        writer.close();

        String zippedFilename = gzipFile(file.getAbsolutePath());
        File zippedFile = new File(zippedFilename);
        zippedFile.deleteOnExit();
        
        AmazonS3 s3 = new AmazonS3Client(propertiesCredentials);

        String bucketName = "druid.yeahmobi.com";
        String dir = "query.result/" + zippedFile.getName();

        s3.putObject(new PutObjectRequest(bucketName, dir, zippedFile));
        return "s3://" + bucketName + "/" + dir;
    }

    public static String Save(String prefix, String data) throws IOException {
        File file = File.createTempFile(prefix + "-", ".csv");
        file.deleteOnExit();

        Writer writer = new OutputStreamWriter(new FileOutputStream(file));
        writer.write(data);
        writer.flush();
        writer.close();

        String zippedFilename = gzipFile(file.getAbsolutePath());
        File zippedFile = new File(zippedFilename);
        zippedFile.deleteOnExit();

        AmazonS3 s3 = new AmazonS3Client(propertiesCredentials);

        String bucketName = "druid.yeahmobi.com";
        String dir = "query.result/" + zippedFile.getName();

        s3.putObject(new PutObjectRequest(bucketName, dir, zippedFile));

        return "s3://" + bucketName + "/" + dir;
    }

    public static String gzipFile(String filename) throws IOException {
        try {
            // Create the GZIP output stream
            String compressedFilename = GzipUtils.getCompressedFilename(filename);
            System.out.println(compressedFilename);
            GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(compressedFilename));

            // Open the input file
            FileInputStream in = new FileInputStream(filename);

            // Transfer bytes from the input file to the GZIP output stream
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();

            // Complete the GZIP file
            out.finish();
            out.close();

            return compressedFilename;
        } catch (IOException e) {
            throw e;
        }
    }
}
